package com.mxw.leetcode.C1二叉树;

import com.mxw.leetcode.C1二叉树.entity.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class T05层序遍历 {

    Queue<TreeNode> queue = new LinkedList<>();

    void levelTraverse(TreeNode root) {

        if (root == null) {
            return;
        }
        queue.offer(root);

        // 从上到下遍历二叉树的每一层
        while (!queue.isEmpty()) {
            int size = queue.size();
            // 从左到右遍历每一层的每个节点
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                // 将下一层节点放入队列
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }

    }
}
